#include"mystdio.h"
#include <sys/types.h>
#include <sys/stat.h> 
#include <fcntl.h>
#include <unistd.h>
#include<string.h>
#include<stdlib.h>

#define flag 0666
#define flush_now 1
#define flush_line 2
#define flush_all 4
_FILE * _fopen(const char * filename ,const char*  mode)
{
	int f = 0;
	int fd = -1;
	if(strcmp("w",mode)==0)
	{
		f = (O_WRONLY|O_CREAT|O_TRUNC);
		 fd = open(filename,f,flag);
	}
	else if(strcmp("r",mode)==0)
	{

		f = (O_RDONLY);
		 fd = open(filename,f);
	}
	else if(strcmp("a",mode)==0)
	{

		f = (O_WRONLY|O_CREAT|O_APPEND);
		 fd = open(filename,f,flag);
	}
	else
		return NULL;
	if(fd ==-1)
		return NULL;
	_FILE * fp  = (_FILE*)malloc(sizeof(_FILE));
	if(fp==NULL)
	{
		return NULL;
	}
	fp->fd = fd;
	fp->flush_mode = flush_now;
	fp->out_pos = 0;
	return fp;

}
int _fwrite(_FILE * fp,const char * msg,int len)
{
	memcpy(&fp->outbuffer[fp->out_pos],msg,len);
	fp->out_pos += len;
	if(fp->flush_mode&flush_line)
	{
		if(fp->outbuffer[fp->out_pos-1]=='\n')
		{
	write(fp->fd,fp->outbuffer,fp->out_pos);
	fp->out_pos = 0;
		}
		else
		{
			return len;

		}
	}
	else if(fp->flush_mode&flush_now)
	{

	write(fp->fd,fp->outbuffer,fp->out_pos);
	fp->out_pos = 0;
	}
	else
	{
		if(fp->out_pos == size)
		write(fp->fd,fp->outbuffer,fp->out_pos);
		fp->out_pos = 0;
	}
	return len;
//	if(pf->flush_mode&&flush_line)
//	{
//		if()
//	}
}
void _fclose(_FILE * fp)
{
	close(fp->fd);
	free(fp);
}
